//var MarkDownIt = require("markdown-it");
//var md = new MarkDownIt();
// md.render

exports.markext = function (str, render) {
    var result = '';
    //str = str.replace(/<\/p>/g, '').replace(/<p>/g, '');
    //str = str.replace(/~%~<\/p>/g, '~%~\n</p>').replace(/<p>~%~/g, '<p>\n~%~');
    var lines = str.split(/\r\n?|\n/);

    var parent_list = [];
    var div_level = 0, last_level = 0;
    var current_content = "";
    var block_enter = false;
    for (var one_line in lines) {
        var trimmed = lines[one_line].trim();

        // Part start mark
        var is_part_start = false;
        if (trimmed.length > 3 && trimmed.charAt(3) != '~') {
            var first3 = trimmed.substring(0, 3);
            if (first3 == '~!~' || first3 == '~@~' || first3 == '~%~') {
                is_part_start = true;
            }
        }

        if (is_part_start) {
            var part_name = trimmed.substring(3);

            if (div_level > 0) {
                result += get_div_content(current_content, div_level, block_enter, render);
                parent_list.push(div_level);
            } else if (current_content.length > 0) {
                result += render(current_content);
            }

            last_level += 1;
            div_level = last_level;
            result += '<a href="javascript:shortmde(' + div_level + ');">' + part_name + '</a> | '
                + '<a href="/?p=' + part_name + '" target=_blank>MORE</a>'
                + get_div2(div_level);

            current_content = "";
            block_enter = true;
        } else if (trimmed == '~%~' || trimmed == '~@~' || trimmed == '~!~') {     // Part end mark
            if (div_level > 0) {
                result += get_div_content(current_content, div_level, block_enter, render);
            }
            div_level = parent_list.length > 0 ? parent_list.pop() : 0;
            current_content = "";
            block_enter = false;
        } else {
            current_content += lines[one_line] + '\n';
        }
    }

    if (current_content.length > 0) {
        result += render(current_content);
    }

    return result;
}

function get_div_content(current_content, level, block_enter, render) {
    if (current_content) {
        return (block_enter ? '<blockquote>' : '')
            + '<div name="mde' + level + '">' + render(current_content) + '</div>'
            + (block_enter ? '</blockquote>' : '');
    } else {
        return '';
    }
}

function get_div2(level) {
    return '<label name="mde' + level + '" style="display:none">...</label>';
}
